﻿using Dyd.BaseService.ConfigManager.Domain;
using Dyd.BaseService.ConfigManager.Domain.Dal;
using Dyd.BaseService.ConfigManager.Domain.Model;
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using Webdiyer.WebControls.Mvc;
using XXF.Db;
using Dyd.BaseService.ConfigManager.Web.Tools;

namespace Dyd.BaseService.ConfigManager.Web.Controllers
{
    [Authorize]
    public class CategoryController : Controller
    {
        private tb_category_dal categoryrDal = new tb_category_dal();
        private tb_log_dal logDal = new tb_log_dal();


        #region 列表
        public ActionResult CategoryIndex(string name, string remark, int pageIndex = 1, int pageSize = 20)
        {
            ViewBag.Name = name;
            ViewBag.Remark = remark;
            int count = 0;
            using (DbConn conn = DbConfig.CreateConn(DataConfig.ConfigMangeConnectString))
            {
                conn.Open();
                IList<tb_category_model> list = categoryrDal.GetPageList(conn, name, remark, pageSize, pageIndex, ref count);
                PagedList<tb_category_model> pageList = new PagedList<tb_category_model>(list, pageIndex, pageSize, count);
                if (Request.IsAjaxRequest())
                {
                    return PartialView("_CategoryIndex", pageList);
                }
                else
                {
                    return View(pageList);
                }
            }
        }

        public JsonResult GetPagingCategoryList(int page = 1, int rows = int.MaxValue, string sort = "Id", string order = "desc")
        {
            int count = 0;

            using (DbConn conn = DbConfig.CreateConn(DataConfig.ConfigMangeConnectString))
            {
                string name = Request["name"];
                string remark = Request["remark"];
                conn.Open();
                IList<tb_category_model> list = categoryrDal.GetPageList(conn, name, remark, rows, page, ref count);

                var total = count;
                var items = list;
                var json = new
                {
                    total = total,
                    rows = list
                };
                return Json(json, JsonRequestBehavior.AllowGet);
            }
        }
        #endregion

        #region 新增
        public ActionResult CategoryAdd()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult CategoryAdd(tb_category_model model)
        {
            using (DbConn conn = DbConfig.CreateConn(DataConfig.ConfigMangeConnectString))
            {
                try
                {
                    conn.Open();
                    if (categoryrDal.IsExist(conn, model))
                    {
                        ModelState.AddModelError("Error", "分类名已存在！");
                        return View(model);
                    }
                    model.createtime = conn.GetServerDate();
                    var id = categoryrDal.Add(conn, model);
                    logDal.Add(conn, string.Format("{0}|{1}|{2}", "添加分类", id, model.name));
                    return RedirectToAction("CategoryIndex");
                }
                catch (Exception exp)
                {
                    ModelState.AddModelError("Error", exp.Message);
                    return View(model);
                }
            }
        }
        #endregion

        #region 修改
        public ActionResult CategoryEdit(int id)
        {
            using (DbConn conn = DbConfig.CreateConn(DataConfig.ConfigMangeConnectString))
            {
                conn.Open();
                var model = categoryrDal.Get(conn, id);
                return View(model);
            }
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult CategoryEdit(tb_category_model model)
        {
            using (DbConn conn = DbConfig.CreateConn(DataConfig.ConfigMangeConnectString))
            {
                try
                {
                    conn.Open();
                    if (categoryrDal.IsExist(conn, model))
                    {
                        ModelState.AddModelError("Error", "分类名已存在！");
                        return View(model);
                    }
                    categoryrDal.Edit(conn, model);
                    logDal.Add(conn, string.Format("{0}|{1}|{2}", "编辑分类", model.id, model.name));

                    return RedirectToAction("CategoryIndex");
                }
                catch (Exception exp)
                {
                    ModelState.AddModelError("Error", exp.Message);
                    return View(model);
                }
            }
        }
        #endregion

        #region 删除
        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult CategoryDel(int id)
        {
            using (DbConn conn = DbConfig.CreateConn(DataConfig.ConfigMangeConnectString))
            {
                try
                {
                    conn.Open();
                    var re = categoryrDal.DelCheck(conn, id);
                    if (!re.Flag)
                    {
                        return Json(re);
                    }
                    else
                    {
                        categoryrDal.Delete(conn, id);
                        logDal.Add(conn, string.Format("{0}|{1}|{2}", "删除分类", id, ""));

                        return Json(new OperateResults { Flag = true, Message = "删除成功！" });
                    }
                }
                catch (Exception exp)
                {
                    return Json(new OperateResults { Flag = false, Message = exp.Message });
                }
            }
        }
        #endregion

        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult ClientReloadConfig(int id)
        {
            using (DbConn conn = DbConfig.CreateConn(DataConfig.ConfigMangeConnectString))
            {
                try
                {
                    conn.Open();
                    var model = categoryrDal.Get(conn, id);

                    RedisHelper.SendCommand(new XXF.BaseService.ConfigManager.SystemRuntime.ConfigNetCommand()
                    {
                        CategoryID = model.id,
                        CommandType = XXF.BaseService.ConfigManager.SystemRuntime.EnumCommandType.ConfigReload,
                        ProjectName = ""
                    });
                    logDal.Add(conn, string.Format("{0}|{1}|{2}", "已经发送客户端重启通知", model.id, model.name));
                    return Json(new OperateResults { Flag = true, Message = "已经发送客户端重启通知！" });
                }
                catch (Exception exp)
                {
                    return Json(new OperateResults { Flag = false, Message = exp.Message });
                }
            }
        }
    }
}
